package zouhaotian.rbac.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import zouhaotian.rbac.exception.FatalException;

import java.lang.reflect.Constructor;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 工具类-单例
 *
 * @auther 邹昊天
 * @since 2025/6/21 18:14
 */
public class SingletonFactory {

    private static final Logger logger = LoggerFactory.getLogger(SingletonFactory.class);

   private static final Map<Class<?>,Object> instanceMap = new ConcurrentHashMap<>();

   public static <T> T getInstance(Class<T> clazz){
       if (clazz == null){

           logger.error("未知的类型");
           throw new FatalException();
       }
       if (!instanceMap.containsKey(clazz)){
           try{
               Constructor<T> constructor = clazz.getDeclaredConstructor();
               constructor.setAccessible(true);
               T singleton = constructor.newInstance();
               instanceMap.put(clazz, singleton);
           } catch (Exception e){
               logger.error("创建单例模式失败：{}", clazz.getSimpleName(), e);
               throw new FatalException(e);
           }

       }
       @SuppressWarnings("unchecked")
       T instance = (T) instanceMap.get(clazz);
       return instance;
   }
}
